import requests
import re
import json
import csv

url = 'https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_aladin_banner'

headers = {
    # 浏览器的基本信息
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Gecko/20100101 Firefox/101.0'
}

# 1.
with open('data.csv', mode='a', encoding='utf-8', newline='') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerow(["area", "curConfirm", "curConfirmRelative", "confirmed", "crued", "died"])
res = requests.get(url=url, headers=headers)

html_data = res.text
json_str = re.findall('"component":\[(.*)\],', html_data)[0]

# 这个是我们的类型
print(type(json_str))
# 这个是将我们的字典转换成为我们的
json_dict = json.loads(json_str)
caselist = json_dict['caseList']

for case in caselist:
    confirmed = case['confirmed']  # 累计确诊
    area = case['area']  # 省份
    curConfirm = case['curConfirm']  # 确诊人数
    curConfirmRelative = case['curConfirmRelative']  # 当前确诊人数
    crued = case['crued']
    died = case['died']
    print(area, curConfirm, curConfirmRelative, crued, died, confirmed)
    with open('data.csv', mode='a', encoding='utf-8', newline='') as f:
        csv_writer = csv.writer(f)
        csv_writer.writerow([area, curConfirm, curConfirmRelative, confirmed, crued, died])
